package cn.com.wangluotongxin.netty.event;

import cn.com.wangluotongxin.netty.constants.MsgType;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.util.Map;

@Slf4j
@Component
public class NettyChannelMessageHandler implements ApplicationListener<NettyChannelMessageEvent> {

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void onApplicationEvent(NettyChannelMessageEvent event) {
        if(event.getChannel() == null) return;
        if(event.getByteBuf() == null) return;
        ByteBuf byteBuf = event.getByteBuf();

        try {
            Map<String, String> messageMap = JSONObject.parseObject(new String(byteBuf.toString(Charset.defaultCharset())), Map.class);
            Integer msgType = MapUtil.getInt(messageMap, "msgType");
            switch (msgType){
                // 登录
                case MsgType.LOGIN:
                    applicationEventPublisher.publishEvent(new LoginEvent(this, event.getChannel(), messageMap));
                    break;
                 // 心跳检查
                case MsgType.HEART_BEAT:
                    applicationEventPublisher.publishEvent(new HeartBeatEvent(this, event.getChannel()));
                    break;
                default:
                    log.info("不支持的消息:{}",byteBuf.toString(Charset.defaultCharset()) );
                    break;
            }
        }catch (Exception ex){
            log.info("信息传递异常:{}",byteBuf.toString(Charset.defaultCharset()) );
        }
    }
}
